package com.yang.demo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.shitou.googleplay.lib.randomlayout.StellarMap;
import com.yang.demo.adapter.StellarMapAdapter;
import com.yang.demo.adapter.StellarMapAdapter2;
import com.yang.demo.adapter.TextTagsAdapter;
import com.yang.demo.adapter.TextTagsAdapter2;
import com.yang.demo.adapter.TextTagsAdapter3;
import com.yang.demo.adapter.TextTagsAdapter4;
import com.yang.demo.greendao.DaoManager;
import com.yang.demo.util.Loader;
import com.yang.demo.util.rxbus.RxBus;
import com.yang.demo.util.rxbus.Subscribe;
import com.yang.demo.view.TagCloudView;
import com.yang.demo.view.cloudtags.KeywordsFlow;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.stellarmap)
    StellarMap stellarMap;
    @BindView(R.id.tag_cloud)
    TagCloudView tagCloudView;
    @BindView(R.id.keyworks_flow)
    KeywordsFlow keywordsFlow;
    @BindView(R.id.tv_hint)
    TextView tvHint;

    public static Activity instance;

    private TextTagsAdapter textTagsAdapter;

    //点击的电影主题
    public static String clickTheme;
    //点击的颜色
    public static int clickColor;
    //点击的关键字
    public static String clickKeyword;
    //点击的导演
    public static String clickDirector;
    //点击的作品
    public static String clickWork;


    //电影主题
    private String[] data = new String[]{"剧情", "动作", "爱情", "惊悚", "悬疑", "喜剧", "战争", "古装"};
    //关键词
    private String[][] keywords = {{"生活", "父亲", "女友", "妻子", "发现", "好友", "丈夫", "结识", "工作", "感情", "爱情", "女孩", "得知", "青年", "男友", "意外", "孩子", "警察", "老板", "朋友"},
            {"江湖", "黑帮", "警方", "杀手", "发现", "好友", "追杀", "警察", "武功", "高手", "手下", "少林", "结识", "前往", "黄飞鸿", "身份", "父亲", "报仇", "女友", "得知"},
            {"爱情", "生活", "感情", "女友", "父亲", "男友", "好友", "女孩", "发现", "结识", "工作", "意外", "朋友", "偶然", "分手", "邂逅", "男人", "丈夫", "某日", "青年"},
            {"警方", "警察", "发现", "女友", "妻子", "调查", "黑帮", "杀手", "好友", "恐怖", "男友", "失踪", "神秘", "重案", "警局", "诡异", "凶手", "女子", "生活", "丈夫"},
            {"发现", "飞花", "探长", "调查", "凶手", "真相", "死者", "女子", "警察", "意外", "失踪", "神秘", "钟朗", "恐怖", "女孩", "诡异", "秘密", "前往", "找到", "身份"},
            {"女友", "生活", "好友", "父亲", "发现", "老板", "爱情", "得知", "男友", "意外", "工作", "找到", "黑帮", "感情", "结识", "公司", "某日", "偶然", "妻子", "朋友"},
            {"日军", "日本", "部队", "敌人", "抗日", "国民党", "八路军", "战士", "抗日战争", "日寇", "红军", "毛泽东", "1937", "战争", "途中", "连长", "率领", "带领", "父亲", "我军"},
            {"江湖", "陆小凤", "武林", "黄飞鸿", "梁山", "得知", "少林", "武功", "飞花", "高手", "朝廷", "前往", "弟子", "发现", "唐伯虎", "捕头", "结识", "追杀", "妻子", "镖局"}};
    //主题颜色
    private Integer[] colors = new Integer[]{R.color.juqing, R.color.dongzuo, R.color.aiqing, R.color.jingsong,
            R.color.xueyi, R.color.kehuan, R.color.zhanzheng, R.color.guzhuagn};


    private TextTagsAdapter2 textTagsAdapter2;
    private TextTagsAdapter3 textTagsAdapter3;
    private TextTagsAdapter4 textTagsAdapter4;

    private List<Model> dataList;
    private List<String> directorList = new ArrayList<>();
    private List<String> worksList;

    private int mTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance = this;
        final long l = System.currentTimeMillis();
        ButterKnife.bind(this);
        RxBus.get().register(this);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.main_blue), 50);
        StatusBarUtil.setDarkMode(this);
        //显示电影主题
        first();

        dataList = DaoManager.getInstance().queryDataList();
        Log.e("list.size", dataList.size() + "");
        Loader.stop();

    }

    private Set<String> names = new HashSet<>();

    private List<String> keyList = new ArrayList<>();

    /**
     * 第一步 展示电影主题
     */
    private void first() {
        mTag = 1;
        tvHint.setText("请选择你喜欢到电影主题");
        tagCloudView.setVisibility(View.GONE);
        //主题用静态标签页展示，数据为固定的数组
        StellarMapAdapter adapter = new StellarMapAdapter(this, colors, data);
        stellarMap.setAdapter(adapter);
        stellarMap.setGroup(0, true);
        stellarMap.setRegularity(5, 5);
    }


    String[] clickStr;

    /**
     * 点击电影主题
     *
     * @param bean
     */
    @Subscribe(code = 1001)
    public void chang(DataBean bean) {
        //记录点击的主题为全局变量，方便后续使用
        Constant.theme = bean.getName();
        //记录点击的主题
        clickTheme = bean.getName();
        //记录点击的颜色
        clickColor = bean.getColor();
        //关键词用3d球view展示,设置adapter
        tagCloudView.setLightColor(ContextCompat.getColor(this, clickColor));
        tagCloudView.setDarkColor(ContextCompat.getColor(this, R.color.main_red));

        clickStr = keywords[bean.getIndex()];
        showKeyword(clickStr);

    }

    List<String> clickList = new ArrayList<>();

    /**
     * 展示关键字
     */
    private void showKeyword(String[] strings) {
        mTag = 2;
        tvHint.setText("选择两个关键词");
        clickList.clear();
        //隐藏静态标签页布局
        stellarMap.setVisibility(View.GONE);
        tagCloudView.setVisibility(View.GONE);
        keywordsFlow.setVisibility(View.VISIBLE);
        keywordsFlow.setDuration(800l);
        keywordsFlow.setOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyword = ((TextView) v).getText().toString();
                clickList.add(keyword);
                if (clickList.size() == 1) {
                    tvHint.setText("已经选" + keyword + ",请再选择一个关键词");
                }
                if (clickList.size() == 2) {
                    //点击两个关键字
                    clickKeywords(clickList);
                }
            }
        });
        feedKeywordsFlow(keywordsFlow, strings);
        keywordsFlow.go2Show(KeywordsFlow.ANIMATION_IN);

    }

    private static void feedKeywordsFlow(KeywordsFlow keywordsFlow, String[] arr) {
        keywordsFlow.clear();
        for (int i = 0; i < KeywordsFlow.MAX; i++) {
            String tmp = arr[i];
            keywordsFlow.feedKeyword(tmp);
        }
    }

    List<String> workList1 = new ArrayList<>();

    private void clickKeywords(List<String> list) {
        //筛选包含关键词的电影简介
        if (directorList.isEmpty()) {
            for (int i = 0; i < dataList.size(); i++) {
                //索引到简介
                String content = dataList.get(i).getContent();
                if (content.contains(list.get(0))) {
                    workList1.add(dataList.get(i).getName());
                    directorList.add(dataList.get(i).getDirector());
                }
                if (content.contains(list.get(1))) {
                    workList1.add(dataList.get(i).getName());
                    directorList.add(dataList.get(i).getDirector());
                }

            }
        }
        showWorkList();
    }

    /**
     * 展示电影
     */
    private void showWorkList() {
        mTag = 3;
        tvHint.setText("请选择您感兴趣的电影");
        List<String> list = new ArrayList<>();
        if (workList1.size() > 16) {
            for (int i = 0; i < 16; i++) {
                list.add(workList1.get(i));
            }
        } else {
            list = workList1;
        }
        textTagsAdapter2 = new TextTagsAdapter2(this, clickColor, list);
        tagCloudView.setAdapter(textTagsAdapter2);
        keywordsFlow.setVisibility(View.GONE);
        tagCloudView.setVisibility(View.VISIBLE);
    }


    /**
     * 点击电影
     *
     * @param bean
     */
    @Subscribe(code = 1002)
    public void clickKeyword(DataBean bean) {
        //记录点击的关键词
        String workName = bean.getName();
        //搜索与点击有关的导演
//        searchDirector(workName);
        showDirector();
    }

    /**
     * 搜索导演
     */
    private void searchDirector(String keyword) {
        //这里就是对数据里的特殊字符进行转义
        keyword = keyword.replace((char) 32, ' ');
        keyword = keyword.trim();
        if (directorList.isEmpty()) {
            for (int i = 0; i < dataList.size(); i++) {
                //索引到到关键词
                String keys = dataList.get(i).getKeyword();
                String theme = dataList.get(i).getType();
                //判断点击到关键字是否存在索引中
                if (keys.contains(keyword) && theme.contains(clickTheme)) {
                    //如果该数据包含了用户点击的关键词与主题，则记录该条数据的导演
                    directorList.add(dataList.get(i).getDirector());
                }
            }
        }

        showDirector();
    }


    /**
     * 展示导演
     */
    private void showDirector() {
        mTag = 4;
        //改变下方提示语
        tvHint.setText("请选择你喜欢的导演");

        List<String> list = new ArrayList<>();
        if (directorList.size() > 16) {
            for (int i = 0; i < 16; i++) {
                list.add(directorList.get(i));
            }
        } else {
            list = directorList;
        }
        textTagsAdapter3 = new TextTagsAdapter3(this, clickColor, list);
        tagCloudView.setAdapter(textTagsAdapter3);

    }


    /**
     * 点击导演
     */
    @Subscribe(code = 1003)
    public void clickD(DataBean bean) {
        //记录点击的导演
        clickDirector = bean.getName();
        //搜索该导演的作品
        searchDirectorWorks(clickDirector);
    }

    /**
     * 搜索该导演的作品
     */
    public void searchDirectorWorks(String director) {
        mTag = 5;
        worksList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            String dir = dataList.get(i).getDirector();
            if (dir.equals(director)) {
                //如果导演和主题都是用户选中的，存储这条作品
                worksList.add(dataList.get(i).getName());
            }
        }
        //创建新adapter用户显示作品
        textTagsAdapter4 = new TextTagsAdapter4(this, clickColor, worksList);
        tagCloudView.setAdapter(textTagsAdapter4);
        Loader.stop();
        tvHint.setText("请选择你想看的电影");
        tagCloudView.setVisibility(View.VISIBLE);
        stellarMap.setVisibility(View.GONE);
    }

    /**
     * 点击作品
     *
     * @param bean
     */
    @Subscribe(code = 1004)
    public void clickWork(DataBean bean) {
        //记录点击的作品
        clickWork = bean.getName();
        //搜索作品详情
        searchWorksDetials(clickWork);
    }


    private void searchWorksDetials(String work) {
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getName().equals(work)) {
                //找到该作品的详情，并跳转进入详情页展示
                Intent intent = new Intent(this, DetailsActivity.class);
                intent.putExtra("image", dataList.get(i).getImg());
                intent.putExtra("piantou", dataList.get(i).getName());
                intent.putExtra("daoyan", dataList.get(i).getDirector());
                intent.putExtra("pinfen", dataList.get(i).getScore());
                intent.putExtra("shijian", dataList.get(i).getYear());
                intent.putExtra("theme", clickTheme);
                intent.putExtra("jianjie", dataList.get(i).getContent());
                startActivity(intent);
                return;
            }


        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unRegister(this);
    }

    private final int INTERVAL_TIME = 2000;
    //最近点击返回键时间
    private long lastClickBackTime = 0;


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mTag == 1) {
                if ((System.currentTimeMillis() - lastClickBackTime) > INTERVAL_TIME) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    lastClickBackTime = System.currentTimeMillis();
                } else {
                    //退出APP
                    finish();
                }
            }
            if (mTag == 2) {
                first();
                stellarMap.setVisibility(View.VISIBLE);
                keywordsFlow.setVisibility(View.GONE);
                mTag = 1;
            }
            if (mTag == 3) {
                showKeyword(clickStr);
            }
            if (mTag == 4) {
                showWorkList();
            }
            if (mTag == 5) {
                showDirector();
            }
        }
        return false;
    }
}
